package com.sdy.dcsb.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.common.model.Response;
import com.sdy.common.utils.Assert;
import com.sdy.dcsb.biz.model.EsbInboundMain;
import com.sdy.dcsb.biz.model.EsbInboundScript;
import com.sdy.dcsb.biz.model.EsbScript;
import com.sdy.dcsb.biz.model.swagger.ScriptConfInfo;
import com.sdy.dcsb.biz.model.swagger.ScriptDetailInfo;
import com.sdy.dcsb.biz.model.swagger.ScriptPageInfo;
import com.sdy.dcsb.biz.model.vo.EsbScriptVo;
import com.sdy.dcsb.biz.service.EsbInboundMainService;
import com.sdy.dcsb.biz.service.EsbInboundScriptService;
import com.sdy.dcsb.biz.service.EsbScriptService;
import com.sdy.dcsb.biz.util.ConditionUtil;
import com.sdy.dcsb.web.util.ChineseUtil;
import com.sdy.mvc.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @author Snaky
 * @date 2020/4/20 15:02
 */
@Slf4j
@Controller
@RequestMapping("/EsbScript")
@Api(tags = "脚本相关接口")
public class EsbScriptController extends BaseController {

    @Autowired
    private EsbScriptService scriptService;
    @Autowired
    private EsbInboundMainService inboundMainService;
    @Autowired
    private EsbInboundScriptService inboundScriptService;

    @GetMapping("/getScriptConf")
    @ApiOperation(value = "查询脚本配置信息" ,response = ScriptConfInfo.class)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "服务id，必传")
    })
    @ResponseBody
    public Response getScriptConf(Integer id) throws Exception{
        Assert.notTrue(ConditionUtil.isValidId(id),"服务id为空");
        return Response.success(inboundScriptService.getScriptConf(id));
    }

    @GetMapping("/pageData")
    @ApiOperation(value = "查询已存在脚本信息", response = ScriptPageInfo.class)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "name", value = "脚本名称，可为空，模糊查询"),
            @ApiImplicitParam(dataType = "Integer", name = "current", value = "当前页，默认为1"),
            @ApiImplicitParam(dataType = "Integer", name = "size", value = "分页大小，默认为10")
    })
    @ResponseBody
    public Response pageData(String name,Integer current,Integer size) throws Exception{
        if(size == null || size <= 0){
            size = 10;
        }
        if(current == null || current <= 0){
            current = 1;
        }
        name = ChineseUtil.decode(name);
        IPage<EsbScriptVo> page = scriptService.getPageData(new Page<>(current, size, 0), name);
        return Response.success(page);
    }

    @GetMapping("/saveScriptConf")
    @ApiOperation(value = "保存脚本配置信息")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "scriptId", value = "脚本id，为空时表示删除关联信息"),
            @ApiImplicitParam(dataType = "Integer", name = "serviceId", value = "服务id,必传")
    })
    @ResponseBody
    public Response save(Integer serviceId, Integer scriptId) throws Exception{
        boolean flagServiceIdValid = ConditionUtil.isValidId(serviceId);
        boolean flagScriptIdValid = ConditionUtil.isValidId(scriptId);

        if(!flagServiceIdValid){
            return Response.error("服务id为空");
        }
        EsbInboundMain inboundMain = inboundMainService.getById(serviceId);
        Assert.isNull(inboundMain,"服务id不存在");

        if(flagScriptIdValid){
            // 脚本id和服务id同时存在，新增/修改关联信息
            EsbScript esbScript = scriptService.getById(scriptId);
            Assert.isNull(esbScript,"脚本id不存在");

            QueryWrapper<EsbInboundScript> wrapper = new QueryWrapper<>();
            wrapper.eq("service_id",serviceId);
            EsbInboundScript inboundScript = inboundScriptService.getOne(wrapper);
            boolean flag;
            if(inboundScript == null){
                inboundScript = new EsbInboundScript();
                inboundScript.setCreateDate(new Date())
                    .setServiceId(serviceId)
                    .setScriptId(scriptId);
                flag = inboundScriptService.save(inboundScript);
            } else {
                inboundScript.setUpdateDate(new Date())
                        .setServiceId(serviceId)
                        .setScriptId(scriptId);
                flag = inboundScriptService.update(inboundScript,wrapper);
            }
            return flag ? Response.success("保存成功"):Response.error("保存失败");
        }
        //根据服务id删除关联信息
        QueryWrapper<EsbInboundScript> wrapper = new QueryWrapper<>();
        wrapper.eq("service_id",serviceId);
        boolean flag = inboundScriptService.remove(wrapper);
        return flag ? Response.success("删除成功"):Response.error("删除失败");

    }

    @GetMapping("/getDetail")
    @ApiOperation(value = "查询脚本详情", response = ScriptDetailInfo.class)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "脚本id")
    })
    @ResponseBody
    public Response getDetail(Integer id) throws Exception{
        Assert.isNull(id,"脚本id为空");
        EsbScriptVo esbScript = scriptService.getDetail(id);
        if(esbScript == null){
            return Response.error("脚本id不存在");
        }
        return Response.success(esbScript);
    }

    @PostMapping(value = "/save", produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "保存脚本信息")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "脚本id,为空时表示新增"),
            @ApiImplicitParam(dataType = "String", name = "name", value = "脚本名称"),
            @ApiImplicitParam(dataType = "String", name = "funcName", value = "脚本函数"),
            @ApiImplicitParam(dataType = "String", name = "content", value = "脚本内容")
    })
    public Response save(@RequestBody JSONObject json) throws Exception{
        Integer id = json.getInteger("id");
        String name = json.getString("name");
        String funcName = json.getString("funcName");
        String content = json.getString("content");

        Assert.isBlank(name,"脚本名称为空");
        Assert.isBlank(funcName,"脚本函数为空");
        Assert.isBlank(content,"脚本内容为空");
        EsbScript esbScript;
        if(ConditionUtil.isValidId(id)){
            esbScript = scriptService.getById(id);
            Assert.isNull(esbScript,"脚本id不存在");
            esbScript.setUpdateDate(new Date());
        } else {
            esbScript = new EsbScript();
            esbScript.setCreateDate(new Date());
        }
        esbScript.setId(id)
                .setName(name)
                .setFuncName(funcName)
                .setContent(content);

        boolean flag = scriptService.saveOrUpdate(esbScript);
        return flag ? Response.success(esbScript):Response.error("保存失败");
    }

    @GetMapping("/delete")
    @ApiOperation(value = "删除脚本信息")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "脚本id，必传")
    })
    @ResponseBody
    public Response delete(Integer id) throws Exception{
        Assert.isNull(id,"脚本id为空");

        EsbScript esbScript = scriptService.getById(id);
        Assert.isNull(esbScript,"脚本id不存在");

        QueryWrapper<EsbInboundScript> wrapper = new QueryWrapper<>();
        wrapper.eq("script_id",id);
        EsbInboundScript inboundScript = inboundScriptService.getOne(wrapper);
        Assert.notNull(inboundScript,"脚本已关联服务，无法直接删除");

        boolean flag = scriptService.removeById(id);
        return flag ? Response.success("删除成功"):Response.error("删除失败");
    }

}
